package com.cuckoo.cuckoo_app2.thread;

import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.dao.Platform;
import com.cuckoo.cuckoo_app2.dao.SiteLink;
import com.cuckoo.cuckoo_app2.model.JavaScriptParameterModel;
import com.cuckoo.cuckoo_app2.model.JavaScriptResponseModel;
import com.cuckoo.cuckoo_app2.utils.JavaScroptConsoleUtils;
import com.cuckoo.cuckoo_app2.utils.JavaScroptParameterUtils;
import com.cuckoo.cuckoo_app2.utils.MD5Utils;
import com.cuckoo.cuckoo_app2.utils.MessageCodeUtils;
import com.cuckoo.cuckoo_app2.utils.NetworkRequestHelperUtils;
import com.google.gson.Gson;
import com.quickjs.JSContext;
import com.quickjs.JSObject;
import com.quickjs.QuickJS;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 监控接任务多线程
 */
public class MonitorTaskTherad {

    /**
     * 当线程被激活时，执行的任务。
     * 主要负责发起网络请求以获取数据。
     */
    public void run(SiteLink siteLink, Platform platform) {
        // 日志记录，标记任务开始执行
        Log.i("TEST", "执行任务的代码 ");
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("url", siteLink.getTaskUrl());
        bodyMap.put("token", platform.getToken());
        bodyMap.put("params", platform.getParams());

        Gson gson = new Gson();

        QuickJS quickJS = QuickJS.createRuntimeWithEventQueue();
        // 创建新的隔离
        JSContext contextParam = quickJS.createContext();
        // 创建新的隔离
        JSContext contextRespon = quickJS.createContext();
        try {
            // 执行前方法
            contextParam.addJavascriptInterface(new MD5Utils(), "md5Utils");
            contextParam.addJavascriptInterface(new JavaScroptConsoleUtils(), "console");
            contextParam.addJavascriptInterface(new JavaScroptParameterUtils(bodyMap), "parameter");

            JSObject parameterObj = contextParam.executeObjectScript(siteLink.getTaskCodeBefore(), "script.js");
            JavaScriptParameterModel parameterModel = new JavaScriptParameterModel();
            parameterModel.setUrl(parameterObj.getString("url"));
            parameterModel.setMediaType(parameterObj.getString("mediaType"));
            parameterModel.setRequestType(parameterObj.getString("requestType"));
            parameterModel.setBody(parameterObj.getString("body"));
            parameterModel.setHeaders(parameterObj.getString("headers"));
            HashMap<String, String> headersMap = gson.fromJson(parameterModel.getHeaders(), HashMap.class);

            // 网络请求异常处理
            String response = "";
            if (parameterModel.getRequestType().equals("POST") && parameterModel.getMediaType().equals("json")) {
                response = NetworkRequestHelperUtils.postJson(
                        parameterModel.getUrl(),
                        parameterModel.getBody(),
                        headersMap
                );
            } else if (parameterModel.getRequestType().equals("POST") && parameterModel.getMediaType().equals("form")) {
                response = NetworkRequestHelperUtils.postForm(
                        parameterModel.getUrl(),
                        parameterModel.getBody(),
                        headersMap
                );
            } else if (parameterModel.getRequestType().equals("GET")) {
                response = NetworkRequestHelperUtils.get(parameterModel.getUrl(), headersMap);
            }

            Log.i("TEST", "接单消息：" + response);
            Map<String, String> responseMap = new HashMap<>();
            responseMap.put("res", response);

            // 定义明确的编码 200接单成功  300登录失败   500其他状态
            contextRespon.addJavascriptInterface(new JavaScroptParameterUtils(responseMap), "response");
            JSObject responseObj = contextRespon.executeObjectScript(siteLink.getTaskCodeAfter(), "script.js");

            JavaScriptResponseModel responseModel = new JavaScriptResponseModel();
            responseModel.setCode(responseObj.getString("code"));
            responseModel.setMessage(responseObj.getString("message"));
            responseModel.setDataKey(responseObj.getString("dataKey"));
            responseModel.setDataValue(responseObj.getString("dataValue"));
            // 判断是否相等
            if (responseModel.getMessage().equals(platform.getMessag())) {
                Log.i("TEST", "信息相同无需更新");
                return;
            }
            sendMessage(MessageCodeUtils.TASK_SERVEICE, platform, responseModel);

        } catch (IOException e) {
            // 服务器链接不上
            JavaScriptResponseModel responseModel = new JavaScriptResponseModel();
            responseModel.setCode("300");
            responseModel.setMessage("服务器链接不上");
            sendMessage(MessageCodeUtils.TASK_SERVEICE, platform, responseModel);
        } finally {
            // 关闭js
            contextParam.close();
            contextParam = null;

            // 关闭js
            contextRespon.close();
            contextRespon = null;

            // 关闭引擎
            quickJS.close();
            quickJS = null;
            gson = null;
        }
    }

    public void sendMessage(MessageCodeUtils codeUtils, Platform platform, JavaScriptResponseModel responseModel) {
        Log.i("TEST", "发送更新消息");
        Messenger mMessenger = MyApplication.getInstances().getMessage();
        Message message = Message.obtain();
        message.what = codeUtils.getCode();

        Map<String, Object> map = new HashMap<>();
        map.put("model", responseModel);
        map.put("data", platform);
        message.obj = map;

        try {
            mMessenger.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


}
